package com.zjgeport.zjgdanger.Analysis;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.code.X;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.zjgeport.zjgdanger.Charts.animation.Easing;
import com.zjgeport.zjgdanger.Charts.charts.PieChart;
import com.zjgeport.zjgdanger.Charts.components.Legend;
import com.zjgeport.zjgdanger.Charts.data.Entry;
import com.zjgeport.zjgdanger.Charts.data.PieData;
import com.zjgeport.zjgdanger.Charts.data.PieDataSet;
import com.zjgeport.zjgdanger.Charts.data.PieEntry;
import com.zjgeport.zjgdanger.Charts.formatter.PercentFormatter;
import com.zjgeport.zjgdanger.Charts.highlight.Highlight;
import com.zjgeport.zjgdanger.Charts.interfaces.datasets.IDataSet;
import com.zjgeport.zjgdanger.Charts.listener.OnChartValueSelectedListener;
import com.zjgeport.zjgdanger.Charts.utils.ColorTemplate;
import com.zjgeport.zjgdanger.Charts.utils.MPPointF;
import com.zjgeport.zjgdanger.CommonActivity;
import com.zjgeport.zjgdanger.LoginActivity;
import com.zjgeport.zjgdanger.OnPortDynamics.TankListActivity;
import com.zjgeport.zjgdanger.R;
import com.zjgeport.zjgdanger.common.LogUtils;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.myApplication;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class CompanyExceptionTJActivity extends CommonActivity implements OnChartValueSelectedListener {

    private PieChart mChart;

    private Typeface tf;

    private List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_exception_tj);
        findTextViewById(R.id.title).setText("企业异常统计");
        initCommonListener();
        initData();
    }

    private void initView()
    {
        mChart = (PieChart)findViewById(R.id.chart1);
        mChart.setUsePercentValues(true);
        mChart.getDescription().setEnabled(false);
        mChart.setExtraOffsets(5, 10, 5, 5);

        mChart.setDragDecelerationFrictionCoef(0.95f);

        tf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        mChart.setCenterTextTypeface(Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf"));
        mChart.setCenterText(generateCenterSpannableText());

        mChart.setExtraOffsets(20.f, 0.f, 20.f, 0.f);

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(0f);
        mChart.setTransparentCircleRadius(0f);

        mChart.setDrawCenterText(false);

        mChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(true);
        mChart.setHighlightPerTapEnabled(true);


        //设置图列可见
        mChart.getLegend().setEnabled(true);
        //设置图列标识的大小
        mChart.getLegend().setFormSize(14);
        //设置图列标识文字的大小
        mChart.getLegend().setTextSize(14);
        //设置图列的位置
        mChart.getLegend().setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
        //设置图列标识的形状
        mChart.getLegend().setForm(Legend.LegendForm.CIRCLE);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        // add a selection listener
        mChart.setOnChartValueSelectedListener(this);

        setData(data.size(), 100);

        mChart.animateY(1400, Easing.EaseInOutQuad);
        // mChart.spin(2000, 0, 360);

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);

        // entry label styling
        mChart.setEntryLabelColor(Color.BLACK);
        mChart.setEntryLabelTypeface(mTfRegular);
        mChart.setEntryLabelTextSize(9f);
    }

    /**
     * 初始化数据列表信息
     */
    private void initData() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("getalarmcomp");
        method.setKvdata(map);
        HttpClient.postdata(new Button(CompanyExceptionTJActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        data.addAll(data1);
                    }

                } else {
                    Toast.makeText(getApplication(),result.getResultMessage(),1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(CompanyExceptionTJActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }

                // 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = WHAT_DID_LOAD_DATA;
                msg.obj = data;
                handler.sendMessage(msg);

            }
        });
    }

    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:
                    initView();
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.pie, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actionToggleValues: {
                for (IDataSet<?> set : mChart.getData().getDataSets())
                    set.setDrawValues(!set.isDrawValuesEnabled());

                mChart.invalidate();
                break;
            }
            case R.id.actionToggleHole: {
                if (mChart.isDrawHoleEnabled())
                    mChart.setDrawHoleEnabled(false);
                else
                    mChart.setDrawHoleEnabled(true);
                mChart.invalidate();
                break;
            }
            case R.id.actionDrawCenter: {
                if (mChart.isDrawCenterTextEnabled())
                    mChart.setDrawCenterText(false);
                else
                    mChart.setDrawCenterText(true);
                mChart.invalidate();
                break;
            }
            case R.id.actionToggleXVals: {

                mChart.setDrawEntryLabels(!mChart.isDrawEntryLabelsEnabled());
                mChart.invalidate();
                break;
            }
            case R.id.actionSave: {
                // mChart.saveToGallery("title"+System.currentTimeMillis());
                mChart.saveToPath("title" + System.currentTimeMillis(), "");
                break;
            }
            case R.id.actionTogglePercent:
                mChart.setUsePercentValues(!mChart.isUsePercentValuesEnabled());
                mChart.invalidate();
                break;
            case R.id.animateX: {
                mChart.animateX(1400);
                break;
            }
            case R.id.animateY: {
                mChart.animateY(1400);
                break;
            }
            case R.id.animateXY: {
                mChart.animateXY(1400, 1400);
                break;
            }
        }
        return true;
    }

    private void setData(int count, float range) {

        float mult = range;

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        for (int i = 0; i < count; i++) {
            HashMap<String,String> dataMap = data.get(i);
            entries.add(new PieEntry(Float.parseFloat(dataMap.get("SCOUNT").toString()), dataMap.get("COMPANY_NAME").toString()+":"+dataMap.get("SCOUNT").toString()));
        }

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");
//        dataSet.setDrawIcons(false);
        dataSet.setSliceSpace(3f);
//        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);
        //dataSet.setSelectionShift(0f);

        dataSet.setValueLinePart1OffsetPercentage(57.f);
        dataSet.setValueLinePart1Length(0.2f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setUsingSliceColorAsValueLineColor(false);

        dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
//        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        data.setValueTypeface(tf);
        mChart.setData(data);

        // undo all highlights
        mChart.highlightValues(null);

        mChart.invalidate();
    }

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.5f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.65f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return null;
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

        if (e == null)
            return;
        Log.i("VAL SELECTED",
                "Value: " + e.getY() + ", xIndex: " + e.getX()
                        + ", DataSet index: " + h.getDataSetIndex());
    }

    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }


}
